import { Component, ElementRef, forwardRef, OnInit, Optional } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
@Component({
  selector: 'app-count',
  templateUrl: './count.component.html',
  styleUrls: ['./count.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CountComponent),
      multi: true
    }
  ]
})
export class CountComponent implements OnInit, ControlValueAccessor  {
  _count: number = 0;

  get count() {
      return this._count;
  }
  
  set count(value: number) {
      this._count = value;
      this.propagateOnChange(this._count);
  }
  constructor(
  ) { }

  ngOnInit(): void {
  }

  add() {
    this.count++;
  }

  dec() {
    this.count--;
  }

  writeValue(value) {
    if(value) {
      this.count = value;
    }
  }

  propagateOnChange: (value: any) => void = (_: any) => {};
  propagateOnTouched: (value: any) => void = (_: any) => {};

  registerOnChange(fn: any) {
      this.propagateOnChange = fn;
  }

  registerOnTouched(fn: any) {
      this.propagateOnTouched = fn;
  }
}
